package scan.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import scan.transaction.TransactionManager;

@Aspect
@Component
public class TransactionAspect {
    //全局事务管理器只有一个
    private static final TransactionManager transactionManager = TransactionManager.getSingleton();

    //只有注解的方法才进行XA事务管理逻辑
    @Pointcut("@annotation(scan.annotation.MyXA)")
    public void XAPointCut() {

    }

    /**
     * @param point
     * @return
     * @throws Throwable
     */
    @Around("XAPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        try{
            // 开启全局事务
            transactionManager.begin();
            // 执行方法
            Object proceed = point.proceed();
            // 询问 RM 分支事务是否准备就绪
            boolean prepareSuccess = transactionManager.prepare();

            if (prepareSuccess) {
                // 开始提交分支事务
                transactionManager.commit();
            } else {
                // 回滚
                transactionManager.rollback();
            }
            return proceed;
        }catch (Exception ex)
        {
            System.out.println(ex);
            try {
                transactionManager.rollback();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }finally {
            return null;
        }
    }
}
